package com.fjnu.controller;

import com.fjnu.common.ResponseResult;
import com.fjnu.dto.ArticleConditionDto;
import com.fjnu.dto.ArticleUpdateDto;
import com.fjnu.entity.Article;
import com.fjnu.service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 文章管理控制器
 */
@RestController
@RequestMapping("/blog-api/v0.1/article")
public class ArticleController {

    @Autowired
    private ArticleService articleService;

    /**
     * 根据文章的查询条件进行查询
     * POST: /blog-api/v0.1/article/list
     */
    @PostMapping("/list")
    public ResponseResult<List<Article>> list(@RequestBody ArticleConditionDto articleCond) {
        try {
            // 这里简单实现分页查询，实际可根据articleCond条件查询
            List<Article> articles = articleService.queryByArticleCondition(articleCond, 1, 10).getData();
            return ResponseResult.success(articles);
        } catch (Exception e) {
            return ResponseResult.error("查询文章列表失败: " + e.getMessage());
        }
    }

    /**
     * 新增文章
     * POST: /blog-api/v0.1/article/add
     */
    @PostMapping("/add")
    public ResponseResult add(@RequestBody Article article) {
        try {
            Article result = articleService.insertArticle(article);
            return ResponseResult.success(result);
        } catch (Exception e) {
            return ResponseResult.error("新增文章失败: " + e.getMessage());
        }
    }

    /**
     * 修改文章
     * POST: /blog-api/v0.1/article/update
     */
    @PostMapping("/update")
    public ResponseResult update(@RequestBody ArticleUpdateDto articleUpdateDto) {
        try {
            int result = articleService.updateArticle(articleUpdateDto);
            if (result > 0) {
                return ResponseResult.success("文章修改成功");
            } else {
                return ResponseResult.error("文章修改失败");
            }
        } catch (Exception e) {
            return ResponseResult.error("修改文章失败: " + e.getMessage());
        }
    }

    /**
     * 发布文章
     * GET: /blog-api/v0.1/article/{id}/publish
     */
    @GetMapping("/{id}/publish")
    public ResponseResult publish(@PathVariable("id") String articleId) {
        try {
            // 这里需要一个用户ID，暂时写死为"1"
            int result = articleService.publishArticle(articleId, "1");
            if (result > 0) {
                return ResponseResult.success("文章发布成功");
            } else {
                return ResponseResult.error("文章发布失败");
            }
        } catch (Exception e) {
            return ResponseResult.error("发布文章失败: " + e.getMessage());
        }
    }
}